//
//  AXFShopViewController.m
//  AXFEightGroup
//
//  Created by ooops on 12/22/16.
//  Copyright © 2016 ya. All rights reserved.
//

#import "AXFShopViewController.h"
#import "AXFShopViewControllerFillProductCell.h"
#import "AXFDataModel.h"
#import "AXFShopOkeyView.h"
#import <objc/message.h>
#import "AXFShoppingButtonView.h"

typedef NS_ENUM(NSUInteger, AXFShopViewControllerTableViewSection) {
    AXFShopViewControllerTableViewSectionAddress = 0,
    AXFShopViewControllerTableViewSectionProduct = 1
};

static NSString *const defaultID                              = @"defaultID";
static NSString *const AXFShopViewControllerFillAddressCellID = @"AXFShopViewControllerFillAddressCellID";
static NSString *const AXFShopViewControllerFillFirstCellID   = @"AXFShopViewControllerFillFirstCellID";
static NSString *const AXFShopViewControllerFillProductCellID = @"AXFShopViewControllerFillProductCellID";


@interface AXFShopViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView                       *productTableView;
@property (nonatomic, strong) NSArray<AXFDataModel *>           *models;
@property (nonatomic, strong) AXFShopOkeyView                   *shopOkeyView;

@end

@implementation AXFShopViewController

- (void)loadView {
    if ( _ModelMgr.productList.count == 0 )
    {
        self.view = nibView(@"AXFShopViewControllerEmpty");
        return;
    }
    [super loadView];
    [self initFillProductView];

    [self configurationNotification];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackTapGR];
    [self addPanGRWithView:self.navigationController.view];
}















- (void)addPanGRWithView:(UIView *)view {
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                            action:@selector(handlePanGR:)];
    [view addGestureRecognizer:panGR];
}











- (void)handlePanGR:(UIPanGestureRecognizer *)panGR {

    UIView *targetView = panGR.view;
    CGPoint pt = [panGR translationInView:targetView];
    if (targetView.centerX + pt.x < targetView.centerX) {
        [UIView animateWithDuration:0.3 animations:^{
            targetView.x = 0;
        }];
        return;
    }

    targetView.center = CGPointMake(targetView.center.x + pt.x, targetView.center.y);
    [panGR setTranslation:CGPointMake(0, 0) inView:targetView];

    CGFloat moveX = targetView.x;


    switch (panGR.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged:
        {

        }
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateEnded:
        {
            if (moveX >= SCREEN_WIDTH * 0.4) {
                [UIView animateWithDuration:0.3 animations:^{
                    targetView.x = SCREEN_WIDTH;
                } completion:^(BOOL finished) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
            }
            else {
                [UIView animateWithDuration:0.3 animations:^{
                    targetView.x = 0;
                }];
            }
        }
            break;
        default:
            break;
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.productTableView reloadData];
}


- (void)dealloc {
    NSLog(@"%s dealloc", __FILE__);
    NotificationRemoveObserver(self);
}




- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (void)handleTapGR:(UITapGestureRecognizer *)tap {
    if (_ModelMgr.productList == nil || _ModelMgr.productList.count == 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }

    [self.view endEditing:YES];
}



#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == AXFShopViewControllerTableViewSectionAddress) {
        return 1;
    }
    return self.models.count + 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    NSString *cellID = [self configurationCELLIDWithIndexPath:indexPath];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    [self configurationCELLModelWithIndexPath:indexPath cell:cell];

    return cell;
}




















- (NSString *)configurationCELLIDWithIndexPath:(NSIndexPath *)indexPath {

    NSString *cellID = nil;
    switch (indexPath.section) {

        case AXFShopViewControllerTableViewSectionAddress:
            cellID = AXFShopViewControllerFillAddressCellID;
            break;

        case AXFShopViewControllerTableViewSectionProduct:
            cellID = (indexPath.row == 0) ? AXFShopViewControllerFillFirstCellID : AXFShopViewControllerFillProductCellID;
            break;

        default:
            cellID = defaultID;
            break;
    }

    return cellID;
}

- (void)configurationCELLModelWithIndexPath:(NSIndexPath *)indexPath cell:(UITableViewCell *)cell {

    AXFDataModel *model = nil;

    switch (indexPath.section) {
        case AXFShopViewControllerTableViewSectionProduct:
        {
            NSInteger row = indexPath.row - 1;
            if (row >= 0) model = self.models[row];
        }
            break;

        default:
            break;
    }

    if (model) {
        [cell setValue:model forKey:@"model"];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}


#pragma mark -


#pragma mark - 创建



- (void)registerCell {

    [self.productTableView registerClass:[UITableViewCell class]
                  forCellReuseIdentifier:defaultID];


    [self.productTableView registerNib:nib(@"AXFShopViewControllerFillAddressCell")
                forCellReuseIdentifier:AXFShopViewControllerFillAddressCellID];

    [self.productTableView registerNib:nib(@"AXFShopViewControllerFillFirstCell")
                forCellReuseIdentifier:AXFShopViewControllerFillFirstCellID];

    [self.productTableView registerClass:[AXFShopViewControllerFillProductCell class]
                  forCellReuseIdentifier:AXFShopViewControllerFillProductCellID];

}

- (void)createSubview {

    UIView *superView = [UIView new];
    [self.view addSubview:superView];
    [superView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    self.productTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.productTableView.delegate = self;
    self.productTableView.dataSource = self;
    self.productTableView.estimatedRowHeight = 120.0;
    self.productTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [superView addSubview:self.productTableView];



    [self registerCell];




    self.shopOkeyView = nibView(@"AXFShopOkeyView");
    [superView addSubview:self.shopOkeyView];


    [self.shopOkeyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(superView);
    }];

    [self.productTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(superView);
        make.bottom.equalTo(self.shopOkeyView.mas_top);
    }];

}

- (void)createBackItem {
    self.navigationItem.leftBarButtonItem = ({
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"v2_goback"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    });
}


- (NSArray<AXFDataModel *> *)models {
    return _ModelMgr.productList;
}


- (void)initFillProductView {
    [self createBackItem];
    [self createSubview];
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

- (void)addBackTapGR {
    [self.view addGestureRecognizer:({
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(handleTapGR:)];
    })];
}



- (void)configurationNotification {
    NotificationCenterAddObserver(self, AXFProductCancelNotification, @selector(productCancelNotification));
}

- (void)productCancelNotification {
    if (self.models.count == 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    [self.productTableView reloadData];
}




#pragma mark -

@end
